package live.zs.securitytokenauthorize.config;

import live.zs.securitytokenauthorize.exception.AccessException;
import live.zs.securitytokenauthorize.security.JwtTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author madison
 * @description
 * @date 2021/7/16 23:08
 */
@Component
public class CustomAuthManager {

    public static final String AUTHORIZATION_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    public static final String ACCESS_TOKEN = "accessToken";
    private static final String PARAM_USERNAME = "username";
    private static final String PARAM_PASSWORD = "password";

    @Autowired
    private JwtTokenManager tokenManager;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private CacheManager cacheManager;

    public String login(HttpServletRequest request) {
        Authentication authenticate;
        try {
            String userName = request.getParameter(PARAM_USERNAME);
            String rawPassword = request.getParameter(PARAM_PASSWORD);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userName, rawPassword);
            authenticate = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
        } catch (AuthenticationException e) {
            throw new AccessException("username or password is not correct!");
        }
        return tokenManager.createToken(authenticate);
    }
}
